<?php
namespace wechat;
use think\Cache;
use think\Session;

class Wechat
{
    private $appid;
    private $secret;

    private function init()
    {
        $wxConfig = config('wx');
        $this->appid = $wxConfig['appid'];
        $this->secret = $wxConfig['app_secret'];
    }

    /**
     * 根据网页code获取access_token
     * @param $code
     * @return mixed
     */
    public function get_web_access_token($code)
    {
//        $access_token = cache('web_access_token');
//        if (!$access_token) {
            $this->init();
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->secret}&code={$code}&grant_type=authorization_code";
            $weixin = file_get_contents($url);
            $array = json_decode($weixin, true); //对JSON格式的字符串进行编码
    $access_token = $array['access_token'];

            Session::set('openid', $array['openid']);
            cache('web_access_token', $access_token, 7200);
//        }
//        var_dump(Session::get('openid'));die;

        return ['access_token' => $access_token, 'openid' => $array['openid']];
    }

    /**
     * 获取微信公众号token
     */
    public function get_access_token()
    {

//        $access_token = cache('access_token');
//        if (!Session::get('access_token')) {
            $this->init();
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->secret}";
            $weixin = file_get_contents($url);
            $array = json_decode($weixin, true); //对JSON格式的字符串进行编码
            $access_token = $array['access_token'];
        Session::set('access_token',$access_token);

           // cache('access_token', $access_token, 7200);
//        }
//        $access_token = Session::get('access_token');

        return $access_token;
    }

    public function get_user_info($openid)
    {
        $access_token = (new Wechat())->get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$openid}&lang=zh_CN";
        $info = file_get_contents($url);
        return json_decode($info, true); //对JSON格式的字符串进行编码
    }

    //js——sdk 获取
    public function get_ticket(){
        $access_token = $this->get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=jsapi";
        $jsapi_ticket = file_get_contents($url);

        $array = json_decode($jsapi_ticket, true);
        return $array['ticket'];

    }
}